package com.itheima;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "java-ai2331";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "001package com.itheima.utils;\n" +
                "\n" +
                "import com.aliyun.oss.*;\n" +
                "import com.aliyun.oss.common.auth.CredentialsProviderFactory;\n" +
                "import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;\n" +
                "import com.aliyun.oss.common.comm.SignVersion;\n" +
                "import org.springframework.stereotype.Component;\n" +
                "import java.io.ByteArrayInputStream;\n" +
                "import java.time.LocalDate;\n" +
                "import java.time.format.DateTimeFormatter;\n" +
                "import java.util.UUID;\n" +
                "\n" +
                "@Component\n" +
                "public class AliyunOSSOperator {\n" +
                "\n" +
                "    private String endpoint = \"https://oss-cn-beijing.aliyuncs.com\";\n" +
                "    private String bucketName = \"java-ai\";\n" +
                "    private String region = \"cn-beijing\";\n" +
                "\n" +
                "    public String upload(byte[] content, String originalFilename) throws Exception {\n" +
                "        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。\n" +
                "        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();\n" +
                "\n" +
                "        // 填写Object完整路径，例如202406/1.png。Object完整路径中不能包含Bucket名称。\n" +
                "        //获取当前系统日期的字符串,格式为 yyyy/MM\n" +
                "        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern(\"yyyy/MM\"));\n" +
                "        //生成一个新的不重复的文件名\n" +
                "        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(\".\"));\n" +
                "        String objectName = dir + \"/\" + newFileName;\n" +
                "\n" +
                "        // 创建OSSClient实例。\n" +
                "        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();\n" +
                "        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);\n" +
                "        OSS ossClient = OSSClientBuilder.create()\n" +
                "                .endpoint(endpoint)\n" +
                "                .credentialsProvider(credentialsProvider)\n" +
                "                .clientConfiguration(clientBuilderConfiguration)\n" +
                "                .region(region)\n" +
                "                .build();\n" +
                "\n" +
                "        try {\n" +
                "            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));\n" +
                "        } finally {\n" +
                "            ossClient.shutdown();\n" +
                "        }\n" +
                "\n" +
                "        return endpoint.split(\"//\")[0] + \"//\" + bucketName + \".\" + endpoint.split(\"//\")[1] + \"/\" + objectName;\n" +
                "    }\n" +
                "\n" +
                "}\n.jpg";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "D:\\images\\1702981762669.jpg";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";
        
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
} 